package com.wispx.gateway.core.context;

import com.wispx.gateway.config.pojo.RouteDefinition;
import com.wispx.gateway.core.filter.FilterChain;
import com.wispx.gateway.core.helper.GatewayContextHelper;
import com.wispx.gateway.core.request.GatewayRequest;
import com.wispx.gateway.core.response.GatewayResponse;
import io.netty.channel.ChannelHandlerContext;
import lombok.Data;

/**
 * 网关上下文
 */
@Data
public class GatewayContext {

    private ChannelHandlerContext nettyContext; // Netty 上下文
    private Throwable throwable; // 请求过程中发生的异常
    private GatewayRequest request; // 网关request
    private GatewayResponse response; // 网关response
    private RouteDefinition routeDefinition; // 路由
    private FilterChain filterChain; // 过滤链
    private boolean keepAlive; // 判断标识，短连接/长连接
    private int curFilterIndex = 0; // 执行到的过滤链的位置
    private boolean isDoPreFilter = true; // 过滤链的前置过滤是否执行完毕

    public GatewayContext(ChannelHandlerContext ctx, GatewayRequest request, RouteDefinition routeDefinition, boolean keepAlive) {
        this.nettyContext = ctx;
        this.request = request;
        this.routeDefinition = routeDefinition;
        this.keepAlive = keepAlive;
    }

    public void doFilter() {
        int size = filterChain.size();
        if (isDoPreFilter) {
            filterChain.doPreFilter(curFilterIndex++, this);
            if (curFilterIndex == size) {
                isDoPreFilter = false; // 前置过滤器已经做完
                curFilterIndex--;
            }
        } else {
            filterChain.doPostFilter(curFilterIndex--, this);
            if (curFilterIndex < 0) {
                // 过滤器全部正常执行完毕，没有异常，向Client写回response
                GatewayContextHelper.writeBack2Client(this);
            }
        }
    }

}
